package cn.szq.concurrent.thread.threadLocal;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.IntStream;

/**
 * @ClassName: ThreadLocalDemo4
 * @Description: 所有的线程都共用一个 simpleDateFormat 对象 添加锁
 * @Author: szq
 * @Date: 2021-10-18 08:20:35
 */
public class ThreadLocalDemo5 {

    public static ExecutorService threadPool = Executors.newFixedThreadPool(16);

    public static void main(String[] args) throws InterruptedException {
        Set<String> result = new HashSet<>();
        IntStream.rangeClosed(1, 1000).forEach(t-> threadPool.submit(() -> {
            String date = new ThreadLocalDemo5().date(t);
            System.out.println(Thread.currentThread().getName() + ":" + date);
            result.add(date);
        }));
        threadPool.shutdown();
        Thread.sleep(1000);
        System.out.println(result.size() == 1000);
    }

    private String date(int i) {
        Date date = new Date(i * 1000);
        SimpleDateFormat simpleDateFormat = ThreadSafeFormatter.dateFormatThreadLocal.get();
        return simpleDateFormat.format(date);
    }
}

class ThreadSafeFormatter{
    public static ThreadLocal<SimpleDateFormat> dateFormatThreadLocal = ThreadLocal.withInitial(() -> new SimpleDateFormat("mm:ss"));
}
